package servlet;

import model.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@WebServlet(name = "changeUserInformation", urlPatterns = "/changeUserInformation")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024, // 1 MB
    maxFileSize = 1024 * 1024 * 10,  // 10 MB
    maxRequestSize = 1024 * 1024 * 15 // 15 MB
)
public class ChangeUserInformationServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user_login.jsp");
            return;
        }

        // 获取表单数据
        String nickname = request.getParameter("changeNickname");
        String email = request.getParameter("changeEmail");
        Part avatarPart = request.getPart("changeAvatar");

        // 更新用户信息
        if (nickname != null && !nickname.trim().isEmpty()) {
            user.setNickname(nickname);
        }
        if (email != null && !email.trim().isEmpty()) {
            user.setEmail(email);
        }

        // 处理头像上传
        if (avatarPart != null && avatarPart.getSize() > 0) {
            String fileName = new Date().getTime() + getFileExtension(avatarPart);
            String uploadPath = getServletContext().getRealPath("/picture");
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            
            avatarPart.write(uploadPath + File.separator + fileName);
            user.setAvatar("/picture/" + fileName);
        }

        // 更新用户信息
        boolean isSuccess = userService.updateUser(user);
        if (isSuccess) {
            // 更新session中的用户信息
            session.setAttribute("user", user);
            request.setAttribute("msg", "个人信息更新成功！");
        } else {
            request.setAttribute("msg", "个人信息更新失败，请重试！");
        }

        request.getRequestDispatcher("/user_center.jsp").forward(request, response);
    }

    private String getFileExtension(Part part) {
        String header = part.getHeader("content-disposition");
        String fileName = header.substring(header.indexOf("filename=\"") + 10,
                header.lastIndexOf("\""));
        return fileName.substring(fileName.lastIndexOf("."));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
} 